<template>
  <a-modal
      :closable="false"
      :confirmLoading="confirmLoading"
      :maskClosable="false"
      :title="title"
      :visible="visible"
      :width="width"
      destroyOnClose
      @afterClose="endDebug"
      @cancel="debugClose"
  >
    <a-card :hoverable="true" size="small" style="width: 100%;margin-bottom:10px;cursor:default" title="连接信息">
      <a-row>
        <a-col :span="8">服务类型：{{ model.type }}</a-col>
        <a-col :span="8">服务名称：{{ model.name }}</a-col>
        <a-col :span="8">地址：{{ model.host }}:{{ model.port }}</a-col>
      </a-row>
    </a-card>
    <a-row :gutter="10">
      <a-col :span="8">
        <a-card :hoverable="true" :title="leftTitle" size="small"
                style="width:300px;height:500px;cursor:default">
          <template slot="extra">
            <a-button :title="'刷新'+leftTitle" icon="reload" shape="circle" type="link" @click="getConnectList"></a-button>
            <a-button v-show="!debugStarted" :disabled="!client.isConnected" ghost icon="play-circle"
                      type="primary" @click="startDebug">开始
            </a-button>
            <a-button v-show="debugStarted" ghost icon="pause-circle" type="danger"
                      @click="endDebug">结束
            </a-button>
          </template>
          <a-list :dataSource="connectList">
            <a-list-item slot="renderItem" slot-scope="item, index">
              <a-list-item-meta :description="item.addr">
                <a-button slot="title" type="link" @click="selectClient(item)">{{ item.name || '找不到实例设备！' }}</a-button>
                <!--                                <a @click="selectClient(item)" slot="title">{{item.name}}</a>-->
                <a-avatar
                    v-if="item.isConnected"
                    slot="avatar"
                    icon="link" style="background-color: #f0f0f0; color: #00A0E9"
                />
                <a-avatar
                    v-if="!item.isConnected"
                    slot="avatar"
                    icon="disconnect" style="background-color: #f0f0f0; color: #00A0E9"
                />
              </a-list-item-meta>
              <a-badge v-if="item.isConnected" status="success"/>
              <a-badge v-if="!item.isConnected" status="default"/>
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card :hoverable="true" size="small" style="margin-bottom: 10px;height:180px;cursor:default">
          <template slot="title">
            <a-button @click="send">发送</a-button>
            <a-divider type="vertical"/>
            <a-checkbox v-model="isSendHex" change="">按16进制发送</a-checkbox>
          </template>
          <template slot="extra">
            <a-button icon="export" type="link" @click="clearSend">清空</a-button>
          </template>
          <a-textarea v-model="sendContent" :rows="4"></a-textarea>
        </a-card>
        <a-card :hoverable="true" size="small" style="height:310px;cursor:default">
          <template slot="title">
            <span v-if="(model.type+'').indexOf('server')!==-1">
                客户端：<a-tag color="blue">{{ client.name }}</a-tag>
            </span>
            <a-divider type="vertical"/>
            <a-checkbox v-model="isReceiveHex">按16进制接收</a-checkbox>
            <a-checkbox v-model="isShowTime">显示时间</a-checkbox>
          </template>
          <template slot="extra">
            <a-button icon="export" type="link" @click="clearReceive">清空</a-button>
          </template>
          <a-textarea v-model="receiveContent" :readOnly="true" :rows="10"></a-textarea>
        </a-card>
      </a-col>
    </a-row>

    <template slot="footer">
      <a-button v-show="!debugStarted" icon="close" type="" @click="debugClose">关闭</a-button>
    </template>

  </a-modal>
</template>

<script>
import {getAction} from '@/api/manage'
import moment from 'moment'

export default {
  name: 'debugServiceModal',
  data() {
    return {
      title: '调试',
      debugStarted: false,
      width: 1000,
      visible: false,
      confirmLoading: false,
      model: {},
      connectList: [],
      client: {},
      isSendHex: false,
      isReceiveHex: false,
      isShowTime: false,
      debugContent: '',
      lockReconnect: false,
      sendContent: '',
      receiveContent: ''
    }
  },
  computed: {
    leftTitle() {
      return (this.model.type + '').indexOf('server') !== -1 ? '客户端列表' : '服务端信息'
    }
  },
  watch: {
    isSendHex(val, oval) {
      this.sendContent = val ? this.stringToHex(this.sendContent) : this.hexToString(this.sendContent)
    }
  },
  mounted() {
  },
  methods: {
    // hex转json字符串,16进制ASCII
    hexToString(hex) {
      let rawStr = hex.trim().split(' ').join('')
      let len = rawStr.length
      if (len % 2 !== 0) {
        this.$message.error('非法格式的ASCII码!')
        return hex
      }
      let curCharCode
      let resultStr = []
      for (let i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16)
        resultStr.push(String.fromCharCode(curCharCode))
      }
      return resultStr.join('')
    },

    // json字符串转hex
    stringToHex(str) {
      if (str === '') {
        return ''
      }
      let arr = []
      for (let i = 0; i < str.length; i++) {
        arr.push(str.charCodeAt(i).toString(16))
      }
      return arr.join(' ')
    },

    send() {
      console.log(this.client)
      if (!this.client.addr) {
        this.$message.error('连接不存在！')
        return
      }
      getAction('network/manage/debug', {address: this.client.addr, message: this.sendContent}).then(res => {
        if (res.success) {
          console.log(res)
          this.$message.success(res.message)

        }
      })
    },
    moment,
    debug(record) {
      this.visible = true
      this.model = record
      this.title = record.name + '调试'
      this.receiveContent = ''
      this.getConnectList(record.id)
    },
    getConnectList() {
      let that = this
      this.client = {}
      getAction(
        '/network/manage/listConnectByAddress',
        {address: this.model.host + ':' + this.model.port}
      ).then(res => {
        if (res.success) {
          that.connectList = res.result
          this.$message.success(res.message)
        }
      })
    },
    selectClient(client) {
      if (client['name'] === undefined || client['name'] === '') {
        this.$message.warning('找不到实例设备！请检查实例配置信息。')
        return
      }
      this.client = client
    },
    startDebug() {
      if (((this.model.type + '').indexOf('server') !== -1) && (this.client.name === undefined)) {
        this.$message.info('请选择客户端')
        return
      }
      this.initWebSocket()
    },
    endDebug() {
    },
    clearReceive() {
      this.receiveContent = ''
    },
    clearSend() {
      this.sendContent = ''
    },
    debugClose() {
      this.visible = false
    },
    appendReceiveContent(text) {
      this.receiveContent += (this.isShowTime ? ('[' + moment().format('YYYY-MM-DD HH:mm:ss') + '] ') : '') + text + '\r\n'
    }
  }
}
</script>

<style scoped>

</style>